package com.hk.Mgr.web.controller.order;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ConstantOrderStatus;
import com.hk.commons.DateUtil;
import com.hk.commons.HqlFilter;
import com.hk.commons.JsonUtils;
import com.hk.commons.RedisCilent;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.order.OrderCreateMsg;
import com.hk.commons.vo.OrderStrMsg;
import com.hk.service.order.IOrderHandle;
import com.hk.service.order.IOrderRouteInfo;
import com.hk.service.order.impl.OrderHandleContent;
import com.hk.service.sys.ISysUser;

@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/hcOrder")
public class DeleteRedisOrder {
	private Logger logger = LoggerFactory.getLogger(DeleteRedisOrder.class);

	private static final String HC_FLAG = "HC_ORDER_";

	@Autowired
	private OrderHandleContent orderContent;

	@Autowired
	private ISysUser userService;

	@Resource(name = "huochaiOrderImpl")
	private IOrderHandle<OrderCreateMsg> huochaiOrderImpl;

	@Value("${hk.logsBaseUrl}")
	private String logsBaseUrl;

	@Autowired
	private IOrderRouteInfo orderRouteService;

	@RequestMapping(value = "/updateRedisOrder", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase<Boolean> update() {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter
				.addSql(" where id in (select userId from com.hk.commons.entity.order.OrderRouteInfo where companyId = 3)");

		List<SysUser> userList = userService.findByFilter(hqlFilter);

		if (userList != null) {
			for (SysUser user : userList) {
				logger.info("updateRedisOrder userId = " + user.getId());
				deleteOrderInRedis(user.getId());
			}
		}

		resp.setResult(true);
		resp.setResultCode(StatusCode.SUCCESS.key());
		return resp;
	}

	@RequestMapping(value = "/check", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase<Boolean> check(Long userId) {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		List<OrderStrMsg> orderInfoList = orderContent.getAll(userId);
		/*
		 * logger.info(" userId = " + userId + " order size = " +
		 * orderInfoList.size());
		 */

		for (OrderStrMsg orderMsg : orderInfoList) {
			logger.info(" orderId = " + orderMsg.getId() + "   status = "
					+ orderMsg.getPayStatus());
		}
		resp.setResult(true);
		resp.setResultCode(StatusCode.SUCCESS.key());
		return resp;
	}

	/**
	 * 将redis 中的order 删除，并且储存在redis 中， 删除的订单在文件中保存
	 * 
	 * @param userId
	 * @param orderInfo
	 * @return
	 */
	public void deleteOrderInRedis(Long userId) {
		List<OrderInfo> orderList = null;

		List<OrderInfo> newList = new ArrayList<OrderInfo>();

		String keyStr = HC_FLAG + userId;

		// 从缓存中获取订单信息
		if (RedisCilent.existsKey(keyStr)) {
			orderList = getOrderListFromRedis(userId);
		}

		logger.info("deleteOrderInRedis orderList userId = " + userId);

		if (orderList == null || orderList.size() == 0) {
			// 如果订单长度为0， 则删除key
			RedisCilent.delKey(keyStr);
		} else if (orderList != null && orderList.size() > 0) {
			// 如果缓存中订单列表不为空则添加，为空则新建

			logger.info("deleteOrderInRedis orderList != null + size = "
					+ orderList.size());
			for (int i = 0; i < orderList.size(); i++) {

				OrderInfo orderInfo = orderList.get(i);

				if (orderInfo != null) {
					// logger.info("deleteOrderInRedis will check order  id  = "+
					// orderInfo.getId());
					Long nowTime = System.currentTimeMillis();
					Long oldTime = orderInfo.getOrderCreatedOn();

					// 01首先将订单保存在文件中
					writeFile(orderInfo);

					// 02保存两日内订单
					if (oldTime != null
							&& (nowTime - oldTime < 1000 * 60 * 60 * 24 * 2)) {
						newList.add(orderInfo);
						logger.info("order will keey in redis keep Time less than 2 days! order Id = "
								+ orderInfo.getId());

						logger.info("DeleteOrderInRedis orderId = "
								+ orderInfo.getId() + "  nowTime = "
								+ DateUtil.longToLongDate(nowTime)
								+ "   oldTime = "
								+ DateUtil.longToLongDate(oldTime));

						// 03保存支付成功的订单
					} else if (orderInfo.getPayStatus() != null
							&& orderInfo.getPayStatus() == ConstantOrderStatus.PAY_STATUS_TRUE) {
						newList.add(orderInfo);
						logger.info("order will keey in redis payStatus = "
								+ orderInfo.getPayStatus() + "  order Id = "
								+ orderInfo.getId());
					} else if (orderInfo.getPayStatus() != null
							&& orderInfo.getPayStatus() == ConstantOrderStatus.PAY_STATUS_NO_CONFIRM) {
						newList.add(orderInfo);
						logger.info("order will keey in redis payStatus = "
								+ orderInfo.getPayStatus() + "  order Id = "
								+ orderInfo.getId());
					} else {
						logger.info("*******Delete order from Redis *******");
						logger.info("Delete order from redis orderId will delete from redis orderId = "
								+ orderInfo.getId()
								+ "  userId = "
								+ orderInfo.getUserId()
								+ " orderPayStatus = "
								+ orderInfo.getPayStatus());
					}
				}
			}
		}

		RedisCilent.setString(keyStr, JsonUtils.toJson(newList));

	}

	/**
	 * add orderInfo into Redis
	 * 
	 * @param orderId
	 * @return
	 */

	private static List<OrderInfo> getOrderListFromRedis(Long userId) {
		List<OrderInfo> orderList = null;

		String keyStr = HC_FLAG + userId;

		// 从缓存中获取订单信息
		if (RedisCilent.existsKey(keyStr)) {

			String orderInfoStr = RedisCilent.getString(keyStr);
			try {

				orderList = JsonUtils.toBean(orderInfoStr, List.class,
						OrderInfo.class);

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return orderList;
	}

	/**
	 * 将订单数据写入文件中
	 * 
	 * @param payRecord
	 */
	public void writeFile(OrderInfo or) {
		Long cts = System.currentTimeMillis();
		String pathName = "hcOrderInfoInRedis-"
				+ DateUtil.transferLongToDate("yyyyMMdd", cts) + ".txt";
		Path filePath = Paths.get(logsBaseUrl + "/hcOrderInfo/" + pathName);
		// Path filePath = Paths.get("D:/Share/redis-2.8.19/" + pathName);
		StringBuilder orderInfoRecordBuild = getOrderInfo(or);
		if (!Files.exists(filePath)) {
			try {
				StringBuilder fileStr = new StringBuilder();

				fileStr.append("订单id|订单创建 时间|订单确认时间|订单交易时间|订单还本付息时间|用户ID|理财师id|支付方式id|预期收益|成功付款金额");
				fileStr.append("0 | | 1\r\n");
				Files.write(filePath, fileStr.toString().getBytes("UTF-8"));
			} catch (IOException e) {
				logger.error("首次写文件失败！");
				e.printStackTrace();
			}
		} else {// 存在则追加
			try {
				Files.write(filePath,
						orderInfoRecordBuild.toString().getBytes("UTF-8"),
						StandardOpenOption.APPEND);
			} catch (IOException e) {
				logger.error("追加写文件失败！");
				e.printStackTrace();
			}

		}

	}

	public StringBuilder getOrderInfo(OrderInfo or) {
		StringBuilder hcRecordStringBuilder = new StringBuilder();

		hcRecordStringBuilder.append(or.getId() + "|" + or.getOrderCreatedOn()
				+ "|" + or.getOrderConfirmDate() + "|" + or.getOrderTradeDate()
				+ "|" + or.getDividendDate() + "|" + or.getUserId() + "|"
				+ or.getFinancialPlannerId() + "|" + or.getPaymentMethodId()
				+ "|" + or.getPaymentId() + "|" + or.getDividend() + "|"
				+ or.getSuccessAmount());

		hcRecordStringBuilder.append("0 | | 1\r\n");

		return hcRecordStringBuilder;
	}

}
